﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;

namespace Screenshot
{
    class ScreenshotApi
    {
        #region 图像相关API
        [DllImport("coredll.dll")]
        private static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);

        [DllImport("coredll.dll")]
        private static extern IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, IntPtr lpInitData);

        [DllImport("coredll.dll")]
        public static extern void MessageBeep(int uType);

        internal static Image ScreenShot(Rectangle rectangle_0)
        {
            unsafe
            {
                Graphics graphic = null;
                Graphics graphic1 = null;
                Image bitmap = null;
                IntPtr zero = IntPtr.Zero;
                IntPtr hdc = IntPtr.Zero;
                try
                {
                    try
                    {
                        bitmap = new Bitmap(rectangle_0.Width, rectangle_0.Height, PixelFormat.Format32bppRgb);
                        graphic = Graphics.FromImage(bitmap);
                        zero = graphic.GetHdc();
                        hdc = CreateDC("DISPLAY", null, null, (IntPtr)0);
                        graphic1 = Graphics.FromHdc(hdc);
                        hdc = graphic1.GetHdc();
                        BitBlt(zero, 0, 0, rectangle_0.Width, rectangle_0.Height, hdc, 0, 0, 13369376);
                    }
                    catch
                    {
                        if (bitmap != null)
                        {
                            bitmap.Dispose();
                        }
                        bitmap = null;
                    }
                }
                finally
                {
                    graphic1.ReleaseHdc(hdc);
                    graphic.ReleaseHdc(zero);
                    graphic1.Dispose();
                    graphic.Dispose();
                }
                return bitmap;
            }
        }
        #endregion
    }
}
